//
//  ZXLoginView.m
//  登录和忘记密码
//
//  Created by maxine on 2016/11/3.
//  Copyright © 2016年 maxine. All rights reserved.
//

#import "SNAccountView.h"
#import "SNForgetViewController.h"
#import "ZXUserInfomation.h"
#import "ZXLoginModel.h"
#import "ZXLoginViewController.h"
#import "HMTabBarController.h"
#import "ManagerViewController.h"
#import "HMNavigationController.h"
#import "ZXForgetController.h"
#import "SNPlanListViewController.h"
#import "SecondViewController.h"


static NSString * __phoneNumber;

#import "ZXRegisterViewController.h"

@interface ZXLoginViewController ()

@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UITextField *phone;
@property (weak, nonatomic) IBOutlet UITextField *password;

@property (weak, nonatomic) IBOutlet UIButton *registerButton;

/** HMNavigationController */
@property (nonatomic,strong) UINavigationController * nav;

@end

@implementation ZXLoginViewController


+ (NSString *)getPhoneNumber{
    return __phoneNumber;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"登录";
    [self.loginButton addTarget:self action:@selector(LoginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //去掉测试帐号.
#if TARGET_IPHONE_SIMULATOR == 1
    NSString * filePath = [[NSBundle mainBundle] pathForResource:@"accountlistTEST11.plist" ofType:nil];
    NSArray * array = [NSArray arrayWithContentsOfFile:filePath];
    
    NSDictionary * accountDict = array.firstObject;
    self.phone.text = accountDict[@"phone"];
    self.password.text = accountDict[@"password"];
    [self addCollectionView];
#else
    /** 免登陆逻辑 , 真机才有效 */
//    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
//    NSString * phoneText = [userDefaults objectForKey:@"phoneKey"];
//    NSString * passwordText = [userDefaults objectForKey:@"passwordKey"];
//    if (phoneText.length>0 ) {
//        self.phone.text = phoneText;
//        if (passwordText.length>0) {
//            self.password.text = passwordText;
//            [self LoginBtnClick:nil];
//            return;
//        }
//    }
#endif
    
    
    //userType = 6 的模拟角色
    //    self.phone.text = @"15874101378";
    //    self.password.text = @"999999";
    //userType = 1 的模拟角色
    //    self.phone.text = @"18600840668";
    //    self.password.text = @"111111";
    //sn_note:=========  ============================ stone 🐳 ===========/
    //    NSString * filePath = [[NSBundle mainBundle] pathForResource:@"accountlist.plist" ofType:nil];
    //    NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    //
    //    NSDictionary * accountDict = dict[@"nongmin"];
    //
    //    self.phone.text = accountDict[@"phone"];
    //    self.password.text = accountDict[@"password"];
    //sn_note:=========  ============================ stone 🐳 ===========/
    
    
    
    
    
    //    self.phone.text = accountDict[@"phone"];
    //    self.password.text = accountDict[@"password"];
    
    
    
    
    //        self.phone.text = @"18976530202";
    //        self.password.text = @"999999";
    //业务代表的模拟数据
    /*
     USERCODE	USERNAME	ORGANID	EMAIL	TEL	USERTYPE	VALID	ROLECODE	ROLENAME
     REP20161129131004	张世福	HZS1611290902	fengshouny@163.com	13159911782	1	1	ucbusiagent	联社业务代表
     REP20161129044949	李国中	HZS1611290902	liguozhong@qq.com	18801012818	1	1	ucbusiagent	联社业务代表
     REP20161129101358	白建峰	HZS1611290902	jeff@qq.com	(null)	1	1	ucbusiagent	联社业务代表
     1480407347137	六六	HZS1611290902	123@qq.com	(null)	1	1	ucbusiagent	联社业务代表
     1480404704160	刘贝	HZS1611290902	1120028286@qq.com	15730256138	1	1	ucbusiagent	联社业务代表
     REP20161129050440	李刚	HZS1611290902	lixinggang@qq.com	13996765435	1	1	busiagent	组织业务代表
     */
    
    
}
- (void)addCollectionView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        SNAccountView * mmView = [[SNAccountView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.registerButton.frame)+15, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - CGRectGetMaxY(self.registerButton.frame)-15)];
        @weakify_self
        [mmView setTapActionBlock:^(NSDictionary * infoDict) {
            @strongify_self
            self.phone.text = infoDict[@"phone"];
            self.password.text = infoDict[@"password"];
        }];
        
        [self.view addSubview:mmView];
    });
}


//判断手机号码格式是否正确
- (BOOL)valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

-(BOOL)checkPassWord
{
    if (self.password.text.length < 6) {
        HUDNormal(@"请输入不小于6位数的密码");
    }else if(self.password.text.length > 32){
        HUDNormal(@"密码长度超长");
    }
    //6-20位数字和字母组成
    NSString *regex = @"^(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([pred evaluateWithObject:self.password.text]) {
        return YES ;
    }else
        return NO;
}



- (void)LoginBtnClick:(id)sender {
    
    if (![self valiMobile:self.phone.text]) {
        HUDNormal(@"请检查您输入的手机号码!");
        return;
    };
    
    if (![self checkPassWord]) {
        HUDNormal(@"密码必须是数字或字母组合");
        return;
    }
    /** 测试方法 */
    //    [self loginMethod];
    //    return;
    //-------------------
    if([ZXHTTPManager connectedToNetwork] == NO){
        //没网
        [SNProgressManager showToView:self.view message:@"网络异常, 请检查网络是否开启" afterDelay:2];
        return;
    }
    HUDLoading(@"正在登录");
    WeakSelf(Wself);
    [[ZXHTTPManager sharedManager]loginWith:self.phone.text passWord:self.password.text completed:^(NSDictionary *jsonDict, NSError *error) {
        HUDStop;
        
        /** 没网的时候注释, 有网的时候打开 , 测试方便... -0 - */
        //-----------------------------------------------------------------------------
        if (error) {
            NSLog(@"error = %@",error);
            HUDNormal(@"请检查您的网络");
            
            return ;
        }
        
        
        HUDNormal(jsonDict[@"message"]);
        NSLog(@"jsonDict = %@",jsonDict);
        
        ZXLoginModel * model = [ZXLoginModel mj_objectWithKeyValues:jsonDict];
        /** 全局保存用户信息 */
        [ZXUserInfomation sharedManager].loginModel = model;
        
        NSLog(@"model.result.count = %ld",model.result.count);
        
        LoginResult * result = model.result.firstObject;
        //此处把用户信息用偏好设置存储,下一个接口会用到 模拟存储
        NSLog(@"result.userType = %@",result.userType);
        //  result.USERTYPE = @"1";
        [[NSUserDefaults standardUserDefaults] setObject:result.userType forKey:@"userType"];
        
        NSLog(@"result.USERID = %@",result.userType);
        
        //        [[ZXHTTPManager sharedManager] getTokenWithUserId:result.userId userName:result.userName phone:result.account role:result.userType completed:^(NSDictionary *jsonDict, NSError *error) {
        [[ZXHTTPManager sharedManager] getTokenWithUserId:result.userId userName:result.userName idCard:result.idCard phone:result.account password:self.password.text role:result.role completed:^(NSDictionary *jsonDict, NSError *error) {
            
            if (error) {
                NSLog(@"%@",[[NSString alloc] initWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding]);
                return ;
            }
            //此处把token用偏好设置存储
            NSLog(@"%@",jsonDict);
            [ZXTokenManager sharedManager].token = jsonDict[@"result"][@"token"];
            NSLog(@"[ZXTokenManager sharedManager].token = %@",[ZXTokenManager sharedManager].token);
            
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            [defaults setObject:jsonDict[@"result"][@"token"] forKey:@"token_key"];
            [defaults synchronize];
            
            
            HMTabBarController *tabVc = [[HMTabBarController alloc] init];
            //MARK: - 888888测试USERTYPE
            //result.userType = [[NSUserDefaults standardUserDefaults] valueForKey:@"userType"];
            
            tabVc.USERTYPE = result.userType;
            //sn_note:========= 存储账号密码 ============================ stone 🐳 ===========/
            {
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                [defaults setObject:self.phone.text forKey:@"phoneKey"];
                [defaults setObject:self.password.text forKey:@"passwordKey"];
                [defaults synchronize];
            }
            //sn_note:=========  ============================ stone 🐳 ===========/
            [Wself presentViewController:tabVc animated:YES completion:nil];
            
            // [self loginMethod];
        }];
    }];
    
}
- (void)loginMethod
{
    //    self.phone.text = @"13645105555";
    //    self.password.text = @"101111";
    
    //领导驾驶舱 8
    if ([self.phone.text isEqualToString:@"13645108888"] && [self.password.text isEqualToString:@"108888"]) {
        __phoneNumber = self.phone.text;
        ManagerViewController *mVc = [[ManagerViewController alloc]init];
        
        self.nav = [[UINavigationController alloc] initWithRootViewController:mVc];
        
        mVc.nav = self.nav;
        
        [self presentViewController:self.nav animated:YES completion:nil];
    }
    //联社 7
    else if([self.phone.text isEqualToString:@"13645107777"] && [self.password.text isEqualToString:@"107777"]){
        __phoneNumber = self.phone.text;
        [[NSUserDefaults standardUserDefaults] setObject:@"7" forKey:@"userType"];
        HMTabBarController *tabVc = [[HMTabBarController alloc]init];
        [self presentViewController:tabVc animated:YES completion:nil];
    }
    //合作社 6
    else if([self.phone.text isEqualToString:@"13645106666"] && [self.password.text isEqualToString:@"106666"]){
        __phoneNumber = self.phone.text;
        [[NSUserDefaults standardUserDefaults] setObject:@"6" forKey:@"userType"];
        HMTabBarController *tabVc = [[HMTabBarController alloc]init];
        [self presentViewController:tabVc animated:YES completion:nil];
    }
    //小农 1 2 1122
    else if([self.phone.text isEqualToString:@"13645101111"] && [self.password.text isEqualToString:@"101111"]){
        __phoneNumber = self.phone.text;
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"userType"];
        HMTabBarController *tabVc = [[HMTabBarController alloc]init];
        [self presentViewController:tabVc animated:YES completion:nil];
    }
    else if([self.phone.text isEqualToString:@"13645102222"] && [self.password.text isEqualToString:@"102222"]){
        __phoneNumber = self.phone.text;
        [[NSUserDefaults standardUserDefaults] setObject:@"2" forKey:@"userType"];
        HMTabBarController *tabVc = [[HMTabBarController alloc]init];
        [self presentViewController:tabVc animated:YES completion:nil];
    }
    else if([self.phone.text isEqualToString:@"13645101122"] && [self.password.text isEqualToString:@"101122"]){
        __phoneNumber = self.phone.text;
        [[NSUserDefaults standardUserDefaults] setObject:@"12" forKey:@"userType"];
        HMTabBarController *tabVc = [[HMTabBarController alloc]init];
        [self presentViewController:tabVc animated:YES completion:nil];
    }
    //大户 3
    else if([self.phone.text isEqualToString:@"13645103333"] && [self.password.text isEqualToString:@"103333"]){
        __phoneNumber = self.phone.text;
        [[NSUserDefaults standardUserDefaults] setObject:@"3" forKey:@"userType"];
        HMTabBarController *tabVc = [[HMTabBarController alloc]init];
        [self presentViewController:tabVc animated:YES completion:nil];
    }
    //农场 5
    else if([self.phone.text isEqualToString:@"13645105555"] && [self.password.text isEqualToString:@"105555"]){
        __phoneNumber = self.phone.text;
        [[NSUserDefaults standardUserDefaults] setObject:@"5" forKey:@"userType"];
        HMTabBarController *tabVc = [[HMTabBarController alloc]init];
        [self presentViewController:tabVc animated:YES completion:nil];
    }
}
- (IBAction)forgetPwdClick:(id)sender {
    
    SNForgetViewController *vc = [[SNForgetViewController alloc]init];
    //    vc.title = @"修改密码";
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)regisClick:(id)sender {
    [self.navigationController pushViewController:[[ZXRegisterViewController alloc]init] animated:YES];
    //    [self.navigationController pushViewController:[[SecondViewController alloc]init] animated:YES];
}


@end
